package com.zbkj.crmeb.chant.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.chant.dao.ChannelProductDao;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.model.ChannelProduct;
import com.zbkj.crmeb.chant.request.BatchPushRequest;
import com.zbkj.crmeb.chant.request.ChannelProductRequest;
import com.zbkj.crmeb.chant.request.ProductPushRequest;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.chant.service.IChannelProductService;
import com.zbkj.crmeb.chant.vo.ChannelProductVo;
import com.zbkj.crmeb.enums.ChannelPushFlagEnum;
import com.zbkj.crmeb.enums.ChannelPushStatusEnum;
import com.zbkj.crmeb.enums.MarkupRateTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.store.model.MarkupRate;
import com.zbkj.crmeb.store.service.MarkupRateService;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * 渠道商户
 */
@Slf4j
@Service
public class ChannelProductImpl extends ServiceImpl<ChannelProductDao, ChannelProduct> implements IChannelProductService {

    @Autowired
    private StoreProductService storeProductService;

    @Autowired
    private IChannelMerchantService channelMerchantService;

    @Autowired
    private IChannelProductService channelProductService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StoreBrandService storeBrandService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private UserService userService;

    @Autowired
    private MarkupRateService markupRateService;
    /**
     * 渠道商品列表
     * @param reqParam
     * @param pageParam
     * @return
     */
    @Override
    public PageInfo<ChannelProductVo> productList(ChannelProductRequest reqParam, PageParamRequest pageParam) {
        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(reqParam.getChannelId());
        if (ObjectUtils.isNotEmpty(channelMerchant)){
            MarkupRate markupRate = markupRateService.getOne(Wrappers.<MarkupRate>lambdaQuery()
                    .eq(MarkupRate::getMerId, channelMerchant.getId())
                    .eq(MarkupRate ::getType, MarkupRateTypeEnum.PLAT_平台加价率.getType())
                    .last("LIMIT 1"));
            reqParam.setChannelMarkupRate(markupRate.getRatio());
            List<String> brandIdsList= JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            reqParam.setBrandIdList(brandIdsList);
            reqParam.setSuppliersIdList(suppliersIdList);
            reqParam.setTempIdList(tempIdList);
        }

        //渠道商品列表
        PageInfo<ChannelProductVo> channelProductPage = storeProductService.selectChannelProductListPage(reqParam, pageParam);

        //处理返回数据
        List<ChannelProductVo> newChannelProductList = new ArrayList<>();
        dealReturntChannelProductList(channelProductPage.getList(), newChannelProductList);
        channelProductPage.setList(newChannelProductList);
        return channelProductPage;
    }

    /**
     * 渠道商品列表 - 处理返回数据
     * @param channelProductList
     */
    private void dealReturntChannelProductList(List<ChannelProductVo> channelProductList, List<ChannelProductVo> newChannelProductList) {
        if (CollectionUtils.isNotEmpty(channelProductList)){
            for (ChannelProductVo vo: channelProductList){
                //类目名称
                String cateName = categoryService.getCategoryName(vo.getCateId());
                vo.setCateName(cateName);

                //品牌名称
                String brandName = storeBrandService.getBrandName(vo.getBrandId());
                vo.setBrandName(brandName);

                //供应商名称
                String suppliersName = supplierService.getSuppliersName(vo.getSuppliersId());
                vo.setSuppliersName(suppliersName);

                //发货地名称
                StockAreaTempEnum tempEnum = StockAreaTempEnum.getByTempId(vo.getTempId());
                vo.setStockAreaName(tempEnum.getStockAreaName());

                newChannelProductList.add(vo);
            }
        }
    }


    /**
     * 更新渠道商品
     *
     * @return
     */
    @Override
    public boolean updateProduct(ChannelProduct entity) {
        //更新数据-重置推送状态-未推送
        entity.setPushStatus(ChannelPushStatusEnum.NOT_PUSH.getCode());
        //默认渠道和更新操作人
        updateProductOperate(entity);
        return channelProductService.saveOrUpdate(entity);
    }

    /**
     * 推送渠道商品
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public boolean pushProduct(ProductPushRequest pushRequest) {
        switch (pushRequest.getType()){
            case 0:
                //批量推送/取消推送
                return batchPushProduct(pushRequest);
            case 1:
                //全部推送
                return allPushProduct(pushRequest);
            default:
                return false;
        }
    }

    /**
     * 推送渠道商品 - 批量推送/取消推送
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public boolean batchPushProduct(ProductPushRequest pushRequest) {
        try {
            List<BatchPushRequest> batchPushParamList = pushRequest.getBatchPushParam();
            if (CollectionUtils.isNotEmpty(batchPushParamList)) {
                for (BatchPushRequest pushReq : batchPushParamList) {
                    ChannelProduct entity = new ChannelProduct();
                    entity.setId(pushReq.getId());
                    entity.setProductBarcode(pushReq.getProductBarcode());
                    entity.setPushFlag(pushReq.getPushFlag());
                    entity.setPushStatus(ChannelPushStatusEnum.NOT_PUSH.getCode());
                    entity.setChannelId(pushReq.getChannelId());
                    //更新操作人
                    updateProductOperate(entity);
                    if (!channelProductService.saveOrUpdate(entity)) {
                        throw new CrmebException();
                    }
                }
            }
        }catch (Exception e){
            throw new CrmebException("批量推送失败");
        }
        return true;
    }

    /**
     * 推送渠道商品 - 条件查询的记录 - 全部推送
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public boolean allPushProduct(ProductPushRequest pushRequest) {
        try {
            ChannelProductRequest productRequest = pushRequest.getAllPushParam();
            if (ObjectUtils.isNotEmpty(productRequest)) {
                List<ChannelProductVo> productIdList = storeProductService.selectChannelProductList(productRequest);
                for (ChannelProductVo vo : productIdList) {
                    ChannelProduct entity = new ChannelProduct();
                    entity.setId(vo.getId());
                    entity.setProductBarcode(vo.getProductBarcode());
                    entity.setPushFlag(ChannelPushFlagEnum.PUSH.getCode());
                    //重置推送状态-未推送
                    entity.setPushStatus(ChannelPushStatusEnum.NOT_PUSH.getCode());
                    //更新操作人
                    entity.setChannelId(pushRequest.getChannelId());
                    updateProductOperate(entity);
                    if (!channelProductService.saveOrUpdate(entity)) {
                        throw new CrmebException();
                    }
                }
            }
        }catch (Exception e){
            throw new CrmebException("全部推送失败");
        }
        return true;
    }

    /**
     * 更新操作人
     * @param entity
     */
    private void updateProductOperate(ChannelProduct entity) {
        //默认渠道
        entity.setChannelId(entity.getChannelId());
        entity.setChannelType(1);
        //当前登录用户id
        Integer userId = userService.getUserId();
        if (null == entity.getId()) {
            entity.setCreateCode(userId);
            entity.setCreateTime(DateUtil.nowDateTime());
        }else{
            entity.setUpdateCode(userId);
            entity.setUpdateTime(DateUtil.nowDateTime());
        }
    }

    /**
     * 根据BarCode更新渠道商品 - 重置推送状态-未推送
     *
     * @return
     */
    @Override
    public boolean updateProductByBarCode(String barCode) {
        if (StringUtils.isNotBlank(barCode)) {
            UpdateWrapper<ChannelProduct> updateWrapper = new UpdateWrapper();
            updateWrapper.lambda().eq(ChannelProduct::getProductBarcode, barCode);
            updateWrapper.lambda().eq(ChannelProduct::getPushFlag, true);
            updateWrapper.lambda().set(ChannelProduct::getPushStatus, ChannelPushStatusEnum.NOT_PUSH.getCode());
            updateWrapper.lambda().set(ChannelProduct::getUpdateTime, DateUtil.nowDateTime());
            return channelProductService.update(updateWrapper);
        }
        return false;
    }
}
